package com.java.Jdbc;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.List;
import java.util.ArrayList;

public class JDBCUtils {
    // 数据库连接信息
    public static final String URL1 = "jdbc:mysql://localhost:3306/aigou?serverTimezone=GMT&useUnicode=true&characterEncoding=UTF-8&useSSL=false";
    public static final String USERNAME1 = "root";
    public static final String PASSWORD1 = "root";
    /**
     * 执行增删改操作
     * @param sql SQL语句
     * @param params 可变参数，SQL语句参数的值
     * @return 影响的行数
     */
    public static int executeUpdate(String sql, Object... params) {
        try (Connection connection = DriverManager.getConnection(URL1, USERNAME1, PASSWORD1);
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }

            int row = preparedStatement.executeUpdate();
            return row;

        } catch (SQLException ex) {
            ex.printStackTrace();
            throw new RuntimeException("数据库操作失败", ex);  // 提供更具描述性的异常消息
        }
    }
    /**
     * 执行查询操作
     * @param clazz 返回的结果集类型
     * @param sql SQL语句
     * @param params 占位符参数
     * @return 泛型集合
     * @param <T> 泛型类型
     */
    public static <T> List<T> executeQuery(Class clazz, String sql, Object... params){
        try(Connection connection = DriverManager.getConnection(URL1, USERNAME1, PASSWORD1)) {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++){
                preparedStatement.setObject(i + 1, params[i]);
            }

            // 执行查询
            ResultSet rs = preparedStatement.executeQuery();
            //创建List集合
            List<T> list = new ArrayList<>();
            //遍历结果集
            while (rs.next()){
                //使用反射机制创建对象
                Object object = clazz.newInstance();
                //给对象属性赋值
                //使用反射获得类中的所有属性
                Field[] fields = clazz.getDeclaredFields();
                //遍历属性
                for (Field field : fields){
                    //获得列名
                    Object value = rs.getObject(field.getName());
                    //给属性赋值
                    field.setAccessible(true);
                    //设置属性值
                    field.set(object, value);
                }
                list.add((T)object);
            }
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}